package com.aiguigu.gulimall.product.exctption;

import com.aiguigu.common.utils.R;
import com.aiguigu.exception.CodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Godc
 * @description 集中处理所有的异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.aiguigu.gulimall.product")
public class GulimallExpection {
    @ExceptionHandler(value = MethodArgumentNotValidException.class) // 指定异常类型
    public R handlerValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题，异常类型:{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item)->{
            String message = item.getDefaultMessage();
            // 获取错误的属性字段名
            String field = item.getField();
            map.put(field,message);
        });
        return R.error(CodeEnum.VALID_EXCETIPON.getCode(),CodeEnum.VALID_EXCETIPON.getMsg()).put("errorData",map);
    }
    @ExceptionHandler(value = Throwable.class) //处理任意异常
    public R handlerException(Throwable throwable){
        return R.error(CodeEnum.UNKNOW_EXCEPTION.getCode(),CodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
